//
//  LHComposeTextView.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/19.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

//@IBDesignable,是xib中能够实时显示placeHolder的内容
@IBDesignable
class LHComposeTextView: UITextView {

    //MARK: --自定义占位文字
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        label.text = "说出你想说的话说出你想说的话说出你想说的话说出你想说的话说出你想说的话说出你想说的话"
        label.numberOfLines = 0
        return label
    }()
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
        //监听文字的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    //监听文字的改变
    @objc private func textChange() {
        placeHolderLabel.hidden = hasText()
    }
    
    //移除监听
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
        
        //监听文字的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    //MARK: --设置占位文字，使能够在外面对占位文字进行修改
    //@IBInspectable,是xib中增加placeHolder这个属性
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    //MARK: --重写font使占位文字的大小随文字的改变而改变
    override var font: UIFont? {
        didSet {
            if font == nil {
                return
            }
            placeHolderLabel.font = font
        }
    }
    
    //MARK: --重写text，作用是使xib中输入text内容回车后隐藏placeHolder内容
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }
    
    private func setupUI() {
        addSubview(placeHolderLabel)
        
        //使用系统的约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 8
    }
}
